package models
/*********************************************************/
/********************本文档为数据库结构文档******************/
/**************RemoteWareHouse的数据结构********************/
/*********************version:1.0*************************/
/****Copyright (c) 2014年 许剑华. All rights reserved******/
/*********************************************************/
import(
	"gopkg.in/mgo.v2/bson"
	"gopkg.in/mgo.v2"
	//"gopkg.in/mgo.v2"
	"fmt"
	"time"
	"github.com/astaxie/beego"
	"strconv"
)

//控制码字相关的结构体
type RemoteControlModel struct {
	StartAddr		[]int
	Code			[]string
	BitLength		[]int
}

//空调相关的控制字
type AcType		struct {
	TemperatureData			[][]string			`valid:"Required;AlphaDash"`								//
	TempSart				[][]int
	TempBitLen				[][]int
	PowerOffModel			RemoteControlModel
	BootModel			    RemoteControlModel
	WindSweepLeftRight		RemoteControlModel
	WindSweepUpDown			RemoteControlModel
	WindAutoModel			RemoteControlModel
	WindHighModel			RemoteControlModel
	WindMidModel			RemoteControlModel
	WindLowModel			RemoteControlModel
	AutoModel			    RemoteControlModel
	HotModel				RemoteControlModel
	CodeModel				RemoteControlModel
	VentilateModel			RemoteControlModel
	DehumidifyModel			RemoteControlModel
	DefaultCode				string		`valid:"Required;AlphaDash"`
}
//键值对结构体
type CommKeyValue struct {
	Key			string		`valid:"Required;AlphaDash"`
	Value		string		`valid:"Required;AlphaDash"`
}
//普通遥控器的数据
type CommonType		struct {

	CodeArry				[]CommKeyValue
}
//用户存储空调数据人结构体
type RemoteWareHouse struct {
	ObjectId 				bson.ObjectId "_id"
	RemoteName				string			`valid:"Required;AlphaDash"`
	No						string			`valid:"Required;AlphaDash"`
	Version					string			`valid:"Required;AlphaDash"`
	DeviceType				int				`valid:"Required;Numeric"`
	Descript				string			`valid:"Required;AlphaDash"`							//描述
	SaveUrl					string                                     //遥控数据存储的位置
	User    				int64           `valid:"Required;Numeric"`                             //上传用户的ID
	UpdateTime    			time.Time
	TimeScale			    int				`valid:"Required;Numeric"`						   //采样电平的宽度

	IRFRQ					int				`valid:"Required;Numeric"`							//载波频率
	One						string
	Zero						string
	S                       string
	A                       string
	B                       string
	C                       string
	D                       string
	E                       string
	BootCode    			string			`valid:"Required;AlphaDash"`							//遥控的开机码字
	PoweroffCode			string			`valid:"Required;AlphaDash"`							//遥控的关机码字
	MatchCode				[]string
	AcCode					AcType
	CommonCode				[]CommKeyValue
}

//func GetOfficialRemote(Factory string,DeviceModel string,DeviceType string)([]ShareRemote,int64,error){
//	o := orm.NewOrm()
//	var mShareRemote []ShareRemote
//	num,err := o.Raw("SELECT * FROM share_remote WHERE factory == ? or device_model == ? or descript", Factory,DeviceModel,DeviceType,Factory).QueryRows(&mShareRemote)
//
//	return mShareRemote,num,err
//}

func GetUpdateTime(time time.Time)([]RemoteWareHouse,int,error){
	session, err := mgo.Dial("127.0.0.1")
	if err != nil {
		beego.Error("mongodb err")
		panic(err)
	}
	defer session.Close()
	// Optional. Switch the session to a monotonic behavior.
	session.SetMode(mgo.Monotonic, true)

	var result []RemoteWareHouse
	c := session.DB("smart_home").C("RemoteWareHouse")
	err = c.Find(nil).All(&result)
	tmp_result := make([]RemoteWareHouse, len(result))
	if err != nil {
		beego.Error("mongodb err",err)
	}
	var index int
	index = 0
	for _,v := range result{
		fmt.Println("v",v)
		fmt.Println("v.UpdateTime.After(time)",v.UpdateTime.After(time))
		fmt.Println("time.After(v.UpdateTime)",time.After(v.UpdateTime))
		if time.After(v.UpdateTime){
			tmp_result[index] = v
			index++
		}
	}
	//num := len(tmp_result)
	return tmp_result,index,err
}
//匹配空调的数据
//@param 	code   string      空调的开机码
//@return   	 RemoteWareHouse      返回空调数据的数组
//@return   	 int                  返回数组的大小
//@return   	 error      返回的错误
func MatchOfficialAcRemote(code string)([]RemoteWareHouse,int,error){
	session, err := mgo.Dial("127.0.0.1")
	if err != nil {
		beego.Error("mongodb err")
		panic(err)
	}
	defer session.Close()
	// Optional. Switch the session to a monotonic behavior.
	session.SetMode(mgo.Monotonic, true)

	var result []RemoteWareHouse
	c := session.DB("smart_home").C("RemoteWareHouse")
	err = c.Find(bson.M{"bootcode": code}).All(&result)

	if err != nil {
		beego.Error("mongodb err",err)
	}

	num := len(result)
	return result,num,err
}
//匹配空调的数据
//@param 	data   *RemoteWareHouse      空调的开机码
//@return   	 RemoteWareHouse      返回空调数据的数组
//@return   	 int                  返回数组的大小
//@return   	 error      返回的错误
func AddOfficialRemote(data *RemoteWareHouse,userID int64)(error){
	session, err := mgo.Dial("127.0.0.1")
	if err != nil {
		beego.Error("mongodb err")
		panic(err)
	}
	defer session.Close()

	fmt.Println("get data")
	// Optional. Switch the session to a monotonic behavior.
	session.SetMode(mgo.Monotonic, true)
	data.User = userID
	data.ObjectId = bson.NewObjectId()
	c := session.DB("smart_home").C("RemoteWareHouse")
	data.UpdateTime = time.Now()
	err = c.Insert(data)
	if err != nil {
		beego.Error("mongodb err",err)
	}
	return err
}

//更新空调的数据
//@param 	ObjectId   string         空调数据的存储ID
//@param    data	 RemoteWareHouse      要更新的空调数据
//@return   	 error      返回的错误
func UpdateOfficialRemote(ObjectId string,data RemoteWareHouse)(error){
	session, err := mgo.Dial("127.0.0.1")
	if err != nil {
		beego.Error("mongodb err")
		panic(err)
	}
	defer session.Close()
//	fmt.Println("get data")
	// Optional. Switch the session to a monotonic behavior.
	session.SetMode(mgo.Monotonic, true)

	c := session.DB("smart_home").C("RemoteWareHouse")
	//err = c.Update(bson.M{"_id": object_Id}, data)
	var o_Id	string
	o_Id = ObjectId
	object_Id := bson.ObjectIdHex(o_Id)
	data.ObjectId = object_Id
	err =c.UpdateId(object_Id, data)

	if err != nil {
		beego.Error("mongodb err",err)

	}
	return err
}

//删除空调的数据
//@param 	ObjectId   string         空调数据的存储ID
//@return   	 error      返回的错误
func DelOfficialRemote(ObjectId string)(error){
	session, err := mgo.Dial("127.0.0.1")
	if err != nil {
		beego.Error("mongodb err")
		panic(err)
	}
	defer session.Close()
	fmt.Println("get data")
	// Optional. Switch the session to a monotonic behavior.
	session.SetMode(mgo.Monotonic, true)
	object_Id := bson.ObjectIdHex(ObjectId)
	c := session.DB("smart_home").C("RemoteWareHouse")
	err = c.RemoveId(object_Id)

	if err != nil {
		beego.Error("mongodb err",err)
	}
	return err
}

//获取官方空调数据的列表
//@param 	     []RemoteWareHouse         空调数据的数组
//@return   	 error      返回的错误
func GetOfficialRemoteList()([]RemoteWareHouse,error){
	var result []RemoteWareHouse
	session, err := mgo.Dial("127.0.0.1")
	if err != nil {
		beego.Error("mongodb err")
		panic(err)
	}
	defer session.Close()
	fmt.Println("get data")
	// Optional. Switch the session to a monotonic behavior.
	session.SetMode(mgo.Monotonic, true)

	c := session.DB("smart_home").C("RemoteWareHouse")
	err = c.Find(nil).All(&result)

	if err != nil {
		beego.Error("mongodb err",err)

	}
	return result, err
}
//通过存储的ID来获取空调数据
//@param 	 objectId    string       空调数据的存储ID
//@return   	 		 RemoteWareHouse      返回的空调数据
//@return   	         error      返回的错误
func GetOfficialRemoteByID(objectId string)(RemoteWareHouse, error){
	var result RemoteWareHouse
	fmt.Println("objectId",objectId)
	session, err := mgo.Dial("127.0.0.1")
	if err != nil {
		beego.Error("mongodb err")
		panic(err)
		return result,err
	}
	defer session.Close()

	session.SetMode(mgo.Monotonic, true)

	c := session.DB("smart_home").C("RemoteWareHouse")
	//mObjectId := new(bson.ObjectId)
	fmt.Println("objectId",objectId)
	var o_Id	string
	o_Id = objectId
	object_Id := bson.ObjectIdHex(o_Id)
	fmt.Println("object_Id",object_Id)
	//	object_Id = bson.ObjectIdHex("548d9ed0e36066320c000002")
	//	fmt.Println("object_Id",object_Id)
	err = c.FindId(object_Id).One(&result)

	if err != nil {
		beego.Error("mongodb err",err)

	}
	return result,err
}
//通过遥控器数据的名字来获取空调数据
//@param 	 remote_name    string            空调数据的存储ID
//@return   	 		 []RemoteWareHouse      返回的空调数据的数组
//@return   	         error      返回的错误
func SearchRemoteByName(remote_name string)([]RemoteWareHouse, error){
	var result []RemoteWareHouse
	session, err := mgo.Dial("127.0.0.1")
	if err != nil {
		beego.Error("mongodb err")
		panic(err)
		return result,err
	}
	defer session.Close()

	session.SetMode(mgo.Monotonic, true)

	c := session.DB("smart_home").C("RemoteWareHouse")

	err = c.Find(bson.M{"remotename": remote_name}).All(&result)
	if err != nil {
		beego.Error("mongodb err",err)
		return result,err
	}
	return result,err
}

func  UserGetNewRemoteData(id string)([]RemoteWareHouse,error){
	user_id ,err:= strconv.ParseInt(id,10,64)
	var RemoteDatas []RemoteWareHouse
	if err != nil{
		return RemoteDatas, err
	}
	user ,err1:= GetUserById(user_id)
	if err1 != nil{
		return RemoteDatas, err1
	}
	RemoteDatas ,_,err1 = GetUpdateTime(user.LastUpdateTime)
	if err1 != nil{
		return RemoteDatas, err1
	}
	return RemoteDatas, err1
}
